/**
 * create by zhike
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.sinapay.marshall;

import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.provider.sinapay.domain.SinapayNotify;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author zhike
 */
@Slf4j
@Component
public class SinapayNotifyUnmarshall extends SinapayAbstractMarshall implements ApiUnmarshal<SinapayNotify, Map<String, String>> {

    @SuppressWarnings("unchecked")
    @Override
    public SinapayNotify unmarshal(Map<String, String> message, String serviceKey) {
        try {
            log.info("异步通知业务参数{}", JSON.toJSONString(message));
            SinapayNotify notify = (SinapayNotify) messageFactory.getNotify(serviceKey);
            String sign = message.get("sign");
            convertUnmarshall(message, notify);
            notify.setService(serviceKey);

            if (Strings.isNotBlank(notify.getSign())) {
                message.remove("sign");
                message.remove("sign_type");
                message.remove("sign_version");
                String signMessage = getMessage(message, false);
                doVerify(signMessage, sign);
            }
            return notify;
        } catch (Exception e) {
            throw new ApiClientException("异步通知 解析失败:" + e.getMessage());
        }

    }
}
